package com.example.android;

//import com.android.future.usb.UsbAccessory;

import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.hardware.usb.*;

public class UsbAccessoryActivity extends Activity {
	private static final String TAG = "USBAccessory";

	/** Called when the activity is first created. */

	UsbManager manager;
	UsbAccessory accessory;
	ParcelFileDescriptor fileDescriptor;
	FileInputStream inputStream;
	FileOutputStream outputStream;
	TextView statusText;
	TextView valueText;
	byte[] buf = new byte[5];

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		Button findButton = (Button) findViewById(R.id.findButton);
		findButton.setOnClickListener(findButtonOnClickListener());
		
		Button valueButton = (Button) findViewById(R.id.valueButton);
		valueButton.setOnClickListener(valueButtonOnClickListener());
		
		Button exitButton = (Button) findViewById(R.id.exitButton);
		exitButton.setOnClickListener(exitButtonOnClickListener());

		statusText = (TextView) findViewById(R.id.statusText);
		valueText = (TextView) findViewById(R.id.value);
	}


	private void findButtonClickListener() {
		final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
		manager = (UsbManager) getSystemService(Context.USB_SERVICE);
		UsbAccessory[] accessories = manager.getAccessoryList();
		accessory = (accessories == null ? null : accessories[0]);
		
		PendingIntent permissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
		IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
		registerReceiver(usbReceiver, filter);

		manager.requestPermission(accessory, permissionIntent);

		String numAccessories = accessories == null ? "0" : String.valueOf(accessories.length);
		String accessoryInfo = accessory == null ? "accessory = null.": accessory.getDescription() + ".";
		statusText.setText("You have " + numAccessories	+ " ADKModules connected. " + accessoryInfo);
	}

	private void openAccessory(UsbManager usbManager, UsbAccessory accessory) {
		Log.d(TAG, "openAccessory: " + accessory);

		fileDescriptor = usbManager.openAccessory(accessory);
		if (fileDescriptor != null) {
			FileDescriptor fd = fileDescriptor.getFileDescriptor();
			inputStream = new FileInputStream(fd);
			outputStream = new FileOutputStream(fd);
		}
	}

	private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
	private final BroadcastReceiver usbReceiver = new BroadcastReceiver() {

		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (ACTION_USB_PERMISSION.equals(action)) {
				synchronized (this) {
					UsbAccessory accessory = (UsbAccessory) intent
							.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);

					if (intent.getBooleanExtra(
							UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
						if (accessory != null) {
							// call method to set up accessory communication
						}
					} else {
						Log.d(TAG, "permission denied for accessory "
								+ accessory);
					}
				}
			}
		}
	};
	
	private OnClickListener findButtonOnClickListener() {
		return new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				findButtonClickListener();
			}
		};
	}

	private OnClickListener valueButtonOnClickListener() {
		return new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				valueText.setText("Reading Value");
				openAccessory(manager, accessory);
				try {
					inputStream.read(buf, 0, 4);
				} catch (IOException e) {
					e.printStackTrace();
				}
				int val = composeInt(buf, 4);
				valueText.setText(String.valueOf(val));
			}
		};
	}

	private OnClickListener exitButtonOnClickListener() {
		return new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				UsbAccessoryActivity.this.finish();
			}
		};
	}

	private int composeInt(byte[] buf, int len) {
		int value = 0;
		for (int ii = 0; ii < len; ii++) {
			value += (buf[ii] & 0xff) << (8 * ii);
		}
		return value;
	}
}
